const { Op } = require('sequelize');

const { getPagination } = require('@utils/tools');

const cart = require('./cart.model');

const goods = require('../goods/goods.model');

module.exports = {
  async cartAdd({ user_id, goods_id }) {
    const goodsInfo = await goods.findByPk(goods_id);

    if (!goodsInfo) return false;

    try {
      const res = await cart.create({
        goods_id,
        user_id,
        number: 1,
        selection: '1',
      });

      return res.dataValues;
    } catch (error) {
      console.log(`\x1B[41m ${error} \x1B[0m`);
    }
  },

  async cartGetList({ page_size, page_num, user }) {
    const { offset, limit } = getPagination(page_num, page_size);

    try {
      const res = await cart.findAndCountAll({
        offset,
        limit,
        attributes: ['id', 'goods_id', 'user_id', 'number', 'selection'],
        where: {
          user_id: user.id,
        },
        include: [
          {
            model: goods,
            as: 'goods',
            attributes: {
              exclude: ['createdAt', 'updatedAt', 'deletedAt'],
            },
          },
        ],
      });

      return res;
    } catch (error) {
      console.log(`\x1B[45m ${error} \x1B[0m`);
    }
  },

  async cartUpdate(data) {
    const { id, ...args } = data;

    const findCart = await cart.findByPk(id);

    if (!findCart) return false;

    try {
      const res = await findCart.update(args);

      return res.dataValues;
    } catch (error) {
      console.log(`\x1B[45m ${error} \x1B[0m`);
    }
  },

  async cartRemove({ id }) {
    try {
      const res = await cart.destroy({
        where: { id },
      });

      return res > 0;
    } catch (error) {
      console.log(`\x1B[45m ${error} \x1B[0m`);
    }
  },

  async cartBulkUpdate({ selection, ids }) {
    console.log(selection, 'selection', ids, 'ids');

    try {
      const [count] = await cart.update(
        { selection },
        { where: { id: { [Op.in]: ids } } }
      );

      return count > 0;
    } catch (error) {
      console.log(`\x1B[41m ${error} \x1B[0m`);
    }
  },
};
